package cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.common;

import cn.schoolwow.quickdao.annotation.IdStrategy;
import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.common.SetInstanceStatementFlow;
import cn.schoolwow.quickdao.module.database.parent.domain.GetStatementSupplier;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.List;

public class SetInsertInstanceStatementFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        Entity entity = (Entity) flowContext.checkData("entity");

        GetStatementSupplier getStatementSupplier = new GetStatementSupplier() {
            @Override
            public String getStatement() {
                List<Property> propertyList = (List<Property>) flowContext.checkData("propertyList");

                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("insert into " + quickDAOConfig.databaseContext.databaseProvider.escape(entity.tableName) + "(");
                for (Property property : propertyList) {
                    if (property.id && property.strategy == IdStrategy.AutoIncrement) {
                        continue;
                    }
                    sqlBuilder.append(quickDAOConfig.databaseContext.databaseProvider.escape(property.column) + ",");
                }
                sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
                sqlBuilder.append(") values(");
                for (Property property : propertyList) {
                    if (property.id && property.strategy == IdStrategy.AutoIncrement) {
                        continue;
                    }
                    sqlBuilder.append((null == property.function ? "?" : property.function) + ",");
                }
                sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
                sqlBuilder.append(")");
                return sqlBuilder.toString();
            }
        };

        flowContext.startFlow(new SetInstanceStatementFlow())
                .putCurrentCompositeFlowData("sqlCacheName", "insert_" + entity.tableName + "_" + quickDAOConfig.databaseContext.databaseProvider.name())
                .putInstanceData(getStatementSupplier, GetStatementSupplier.class)
                .execute();
    }

    @Override
    public String name() {
        return "设置插入实例的SQL语句";
    }

}
